/**
 * 系统公共的action
 */

DC.action.SysAction = {
	/**
	 * 初始化用户数据
	 * @param ojb
	 */
	initUserInfo : function(obj) {
		DC.front.variable.SYS_CURRENTUSER.id = obj.id;
	    DC.front.variable.SYS_CURRENTUSER.username = obj.username;
	    DC.front.variable.SYS_CURRENTUSER.realName = obj.realName;
	    DC.front.variable.SYS_CURRENTUSER.email = obj.email;
	    DC.front.variable.SYS_CURRENTUSER.password = obj.password;
	    DC.front.variable.SYS_CURRENTUSER.sex = obj.sex;
	    DC.front.variable.SYS_CURRENTUSER.birthday = new Date(obj.birthday).format('Y-m-d');
	    DC.front.variable.SYS_CURRENTUSER.points = obj.point;
	    DC.front.variable.SYS_CURRENTUSER.loginTimes = obj.loginTimes;
	    DC.front.variable.SYS_CURRENTUSER.lastSignTime = new Date(obj.lastSignTime).format('Y-m-d H:i:s');
	    if (obj.notes != undefined && obj.notes != '') {
	    	DC.front.variable.SYS_CURRENTUSER.notes = obj.notes;
	    }
	    
	},
	/**
	 * 用户注销
	 */
	logout : function() {
		var msg = 'Are you sure logout the system?';
		Ext.MessageBox.confirm('Confim Win', msg, function(btn) {
			if (btn == 'yes') {
				window.location.href="logout.action";
			};
		});
	},
	buildProject : function() {
		if(DC.obj.explorer_treePanel) {
			var selectedNode = DC.obj.explorer_treePanel.getSelectionModel().getSelectedNode();
			if (selectedNode.getDepth() == 1) {
				var html = '<div class="progress" id="building_progress">' + 
				               '<span for=".">Building, please wait</span>' +
				    	       '<img src="././image/ico_progerssbar_editnplace.gif" alt="checkout"></img>' +
				           '</div>';
				DC.obj.msg_tabPanel.setActiveTab(1);
				DC.obj.msg_tabPanel.progressPanel.update(html);
        		var projectName = selectedNode.attributes.text;
				Ext.Ajax.request({
				    url : DC.url.BUILD_PROJECT,
				    method : 'POST',
				    params : {
				    	"cProject.projectName" : projectName
				    },
				    success : function(response, options){
					    var res = Ext.util.JSON.decode(response.responseText);
					    var arr = res.msg.split("\n");
					    var tpl = null;
					    if(res.success){// 判断请求是否成功
						   tpl = new Ext.XTemplate(  
						        '<div class="build_msg">',  
						            '<tpl for=".">',
					                	'<p><font color=red>{.}</font></p>',
						            '</tpl>',  
						        '</div>'
						    );
					    } else {
						    tpl = new Ext.XTemplate(  
						        '<div class="build_msg">',  
						            '<tpl for=".">',
					                	'<p>{[this.check(xindex, values)]}</p>',
						            '</tpl>',  
						        '</div>', {
						        	check : function (index, value) {  
					                    if(index == 1 ){  
					                        return "<font color=red>"+value+"</font>";  
					                    } else {  
					                        return value;  
					                    } 
					                }  
						        } 
						    );
					    }
					    
					    tpl.compile(); // 对模板进行编译,速度比较快.
					    DC.obj.msg_tabPanel.progressPanel.update('');
					    DC.obj.msg_tabPanel.setActiveTab(0);
					    tpl.overwrite(DC.obj.msg_tabPanel.getActiveTab().body, arr); // 把数据填充到模板中去,并呈现到目标组件
					    DC.obj.explorer_treePanel.reloadData();
				    },
				    failure : function(response, options){
                    	Ext.example.msg('Verification Win', response.responseText, 'error');
				    }
			    });
        	}
		}
	},
	
	runProject : function() {
		if(DC.obj.explorer_treePanel) {
			var selectedNode = DC.obj.explorer_treePanel.getSelectionModel().getSelectedNode();
			var nodeName = selectedNode.attributes.text;
			if (selectedNode.getDepth() >= 2 && selectedNode.isLeaf() && nodeName.lastIndexOf(".java") > 0) {
				var html = '<div class="progress" id="building_progress">' + 
				               '<span for=".">Building, please wait</span>' +
				    	       '<img src="././image/ico_progerssbar_editnplace.gif" alt="checkout"></img>' +
				           '</div>';
				DC.obj.msg_tabPanel.setActiveTab(1);
				DC.obj.msg_tabPanel.progressPanel.update(html);
				var nodePath = DC.obj.explorer_treePanel.getFilePath(selectedNode);
        		var projectName =  nodePath.substring(0, nodePath.indexOf('/'));
        		var array = selectedNode.getPath().split('/');
        		var path = '';
    			for (var i = 4, len = array.length; i < len; i++) {
    				path = path + DC.obj.explorer_treePanel.getNodeById(array[i]).attributes.text + ".";
    			}
    			path.substring(0, path.length - 1);
        		var pac = path.substring(0, path.indexOf('.java'));
				Ext.Ajax.request({
				    url : DC.url.RUN_PROJECT,
				    method : 'POST',
				    params : {
				    	"cProject.projectName" : projectName,
				    	"mainFile" : pac
				    },
				    success : function(response, options){
					    var res = Ext.util.JSON.decode(response.responseText);
					    var arr = res.msg.split("\n");
					    var tpl = null;
					    if(res.success){// 判断请求是否成功
						   tpl = new Ext.XTemplate(  
						        '<div class="build_msg">',  
						            '<tpl for=".">',
					                	'<p>{.}</p>',
						            '</tpl>',  
						        '</div>'
						    );
					    } else {
						    tpl = new Ext.XTemplate(  
						        '<div class="build_msg">',  
						            '<tpl for=".">',
					                	'<p>{[this.check(xindex, values)]}</p>',
						            '</tpl>',  
						        '</div>', {
						        	check : function (index, value) {  
					                    if(index == 1 ){  
					                        return "<font color=red>"+value+"</font>";  
					                    } else {  
					                        return value;  
					                    } 
					                }  
						        } 
						    );
					    }
					    
					    tpl.compile(); // 对模板进行编译,速度比较快.
					    DC.obj.msg_tabPanel.progressPanel.update('');
					    DC.obj.msg_tabPanel.setActiveTab(0);
					    tpl.overwrite(DC.obj.msg_tabPanel.getActiveTab().body, arr); // 把数据填充到模板中去,并呈现到目标组件
					    DC.obj.explorer_treePanel.reloadData();
				    },
				    failure : function(response, options){
                    	Ext.example.msg('Verification Win', response.responseText, 'error');
				    }
			    });
        	}
		}
	},
	
	deleteNode : function(node) {
		var msg = "";
		var text = node.attributes.text;
		if (node.isLeaf()) {
			msg = "Are you sure delete the \"" + text + "\" file?";
		} else {
			msg = "Are you sure delete the \"" + text + "\" folder?";
		}
		Ext.MessageBox.confirm('Confim Win', msg, function(btn) {
			if (btn == 'yes') {
				var parentPath = DC.obj.explorer_treePanel.getNodePath(node);
				DC.util.CommonAction.loadMask("Delete...");
				Ext.Ajax.request({
				    url : DC.url.DELETE_FILE,
				    method : 'POST',
				    params : {
				    	"depth" : node.getDepth(),
				    	"cfile.fileName" : text,
				    	"cfile.filePath" : parentPath + "/" + text
				    },
				    success : function(response, options){
					    var res = Ext.util.JSON.decode(response.responseText).returnText;
					    if(res.success){// 判断请求是否成功
						   //DC.obj.explorer_treePanel.reloadData(null);
					    	node.remove(true);
					    } else {
		                    Ext.example.msg('Prompt', res.msg, 'prompt');
					    }
					    DC.util.CommonAction.unMask();
				    },
				    failure : function(response, options){
                    	Ext.example.msg('Verification Win', response.responseText, 'error');
                    	DC.util.CommonAction.unMask();
				    }
			    });
			};
		});
	},
	
	closeProject : function(id, name) {
		DC.util.CommonAction.loadMask("Closing...");
		Ext.Ajax.request({
		    url : DC.url.CLOSE_PROJECT,
		    method : 'POST',
		    params : {
		    	'cProject.id' : id,
		    	'cProject.projectName' : name
		    },
		    success : function(response, options){
		    	DC.util.CommonAction.unMask();
		    	var res = Ext.util.JSON.decode(response.responseText);
		    	if (res.success) {
		    		DC.obj.explorer_treePanel.getNodeById(id).remove(true);
		    	} else {
		    		
		    	}
		    },
		    failure : function(response, options){
            	Ext.example.msg('Verification Win', response.responseText, 'error');
		    }
	    });
	},
	
	saveAllOpenFile : function(obj) {
		var tabItems = DC.obj.editor_tabPanel.items;
		
		var filePaths = new Array();
		for (var i = 1, len = tabItems.length; i < len; i++) {
			var field = tabItems.items[i].items.items[0];
			filePaths.push(field.getParentPath() + "/" + field.getFileName());
		}
		var tpl = new Ext.XTemplate(  
		        '<div class="progress">',  
	            '<tpl for=".">',
                	'<div id="{.}" class="progress_item"></div>',
	            '</tpl>',  
	        '</div>'
	    );
		tpl.compile(); // 对模板进行编译,速度比较快.
		DC.obj.msg_tabPanel.setActiveTab(1);
	    tpl.overwrite(DC.obj.msg_tabPanel.getActiveTab().body, filePaths);
	    var pros = new Array();
	    for (var i = 0, len = filePaths.length; i < len; i++) {
	    	var pro = new Ext.ProgressBar({
	            text : filePaths[i],
	            cls : 'left-align',
	            renderTo : filePaths[i]
	        });
	    	pros.push(pro);
		}
	    
	    for (var i = 1, len = tabItems.length; i < len; i++) {
	    	var field = tabItems.items[i].items.items[0];
	    	var parentPath = field.getParentPath();
			var fileName = field.getFileName();
			var fileType = field.getFileType();
			var text = field.getCode();
			//pros[i - 1].updateProgress();
		    
			Ext.Ajax.request({
			    url : DC.url.SAVE_FILE,
			    method : 'POST',
			    params : {
			    	"cfile.parentPath" : parentPath,
			    	"cfile.fileName" : fileName,
			    	"cfile.fileType" : fileType,
			    	"cfile.text" : text
			    },
			    success : function(response, options){
				    var res = Ext.util.JSON.decode(response.responseText).returnText;
				    if(res.success){// 判断请求是否成功
				    	//pros[i - 1].updateProgress(1, 'finished', 'finished');
				    } 
			    },
			    failure : function(response, options){
			    	
			    }
			});
			if (pros[i - 1] != undefined) {
				Runner.run(pros[i - 1], filePaths[i - 1], 12, function(){
					if (pros[i - 1] != undefined) {
						pros[i - 1].reset();
						pros[i - 1].updateText('Done.');
					}
		        });
			}
		}
	},
	
	saveFile : function(obj) {
		var field = obj || Ext.getCmp(DC.obj.editor_tabPanel.getActiveTab().getId() + '_field');
		DC.util.CommonAction.loadMask("Save Data...");
		Ext.Ajax.request({
		    url : DC.url.SAVE_FILE,
		    method : 'POST',
		    params : {
		    	"cfile.parentPath" : field.getParentPath(),
		    	"cfile.fileName" : field.getFileName(),
		    	"cfile.fileType" : field.getFileType(),
		    	"cfile.text" : field.getCode()
		    },
		    success : function(response, options){
		    	DC.util.CommonAction.unMask();
			    var res = Ext.util.JSON.decode(response.responseText).returnText;
			    if(!res.success){// 判断请求是否成功
			    	 if (res.type == 'WARNING') {
                    	DC.util.CommonAction.showMessage('Verification Win', res.msg, Ext.MessageBox.WARNING);
                    } else {
                    	DC.util.CommonAction.showMessage('Application Prompt Win', res.msg, Ext.MessageBox.ERROR);
                    }
			    } 
		    },
		    failure : function(response, options){
		    	DC.util.CommonAction.unMask();
			    DC.util.CommonAction.showMessage('Prompt Win', response.responseText, Ext.MessageBox.ERROR);
		    }
	    });
	},
	
	downloadZipFile : function(url) {
		var selectedNode = DC.obj.explorer_treePanel.getSelectionModel().getSelectedNode();
		/*if (!Ext.fly('test')) {   
	        var frm = document.createElement('form');   
	        frm.id = 'test';   
	        frm.name = id;   
	        frm.style.display = 'none';   
	        document.body.appendChild(frm);   
	    }  */ 
		var nodePath = DC.obj.explorer_treePanel.getSelectedNodePath();
		nodePath = nodePath.substring(0, nodePath.length - 1);
		var nodeName = selectedNode.attributes.text;
		if (selectedNode.isLeaf()) {
			nodeName = nodeName.substring(0, nodeName.lastIndexOf('.'));
		}
		
		if (url) {
			window.open(url + "?filePath=" + nodePath + "&fileName=" + nodeName);
		} else {
			window.open(DC.url.DOWNLOAD_ZIPFILE + "?filePath=" + nodePath + "&fileName=" + nodeName);
		}
		
		/*Ext.Ajax.request({   
	        url : url,  
	        method : 'POST',     
	        isUpload : true,  
	        params : {
	        	filePath : DC.obj.explorer_treePanel.getSelectedNodePath(),
	        	fileName : nodeName
	        },
	         success:function(response, options){  
		        var obj = Ext.decode(response.responseText);  
		        console.log(obj);//可以到火狐的firebug下面看看obj里面的结构  
		        //加入getPath返回的json为{'path':'upload/abc.jpg'}  
		        window.location.href = obj.path;//这样就可以弹出下载对话框了  
		    }  
	    });*/
	},
	/**
	 * 下载单个文件
	 * @param url
	 */
	downloadFile : function() {
		var selectedNode = DC.obj.explorer_treePanel.getSelectionModel().getSelectedNode();
		if (selectedNode.isLeaf()) {
			var nodePath = DC.obj.explorer_treePanel.getFilePath(selectedNode);
			var nodeName = selectedNode.attributes.text;
			window.open(DC.url.DOWNLOAD_FILE + "?filePath=" + nodePath + "&fileName=" + nodeName);
		}
	},
	
	downloadAndBuildProject : function() {
		if(DC.obj.explorer_treePanel) {
			var selectedNode = DC.obj.explorer_treePanel.getSelectionModel().getSelectedNode();
			if (selectedNode.getDepth() == 1) {
        		var projectName = selectedNode.attributes.text;
        		DC.util.CommonAction.loadMask("BuildAndDownload...");
				Ext.Ajax.request({
				    url : DC.url.BUILD_PROJECT,
				    method : 'POST',
				    params : {
				    	"cProject.projectName" : projectName
				    },
				    success : function(response, options){
				    	DC.util.CommonAction.unMask();
					    var res = Ext.util.JSON.decode(response.responseText);
					    var arr = res.msg.split("\n");
					    var tpl = null;
					    if(res.success){// 判断请求是否成功
						   tpl = new Ext.XTemplate(  
						        '<div class="build_msg">',  
						            '<tpl for=".">',
					                	'<p><font color=red>{.}</font></p>',
						            '</tpl>',  
						        '</div>'
						    );
						   tpl.compile(); // 对模板进行编译,速度比较快.
						   DC.obj.msg_tabPanel.setActiveTab(0);
						   tpl.overwrite(DC.obj.msg_tabPanel.getActiveTab().body, arr); // 把数据填充到模板中去,并呈现到目标组件
						   DC.action.SysAction.downloadZipFile(); // 打包下载项目
					    } else {
						    tpl = new Ext.XTemplate(  
						        '<div class="build_msg">',  
						            '<tpl for=".">',
					                	'<p>{[this.check(xindex, values)]}</p>',
						            '</tpl>',  
						        '</div>', {
						        	check : function (index, value) {  
					                    if(index == 1 ){  
					                        return "<font color=red>"+value+"</font>";  
					                    } else {  
					                        return value;  
					                    } 
					                }  
						        } 
						    );
						    tpl.compile(); // 对模板进行编译,速度比较快.
						    DC.obj.msg_tabPanel.setActiveTab(0);
						    tpl.overwrite(DC.obj.msg_tabPanel.getActiveTab().body, arr); // 把数据填充到模板中去,并呈现到目标组件
						    Ext.MessageBox.confirm('Confim Win', 'Build fail, are you sure download this project?', function(btn) {
						    	if (btn == 'yes') {
						    		DC.action.SysAction.downloadZipFile();
						    	}
						    });
					    }
					    
					    
				    },
				    failure : function(response, options){
				    	DC.util.CommonAction.unMask();
                    	Ext.example.msg('Verification Win', response.responseText, 'error');
				    }
			    });
        	}
		}
	}
};

var Runner = function(){
    var f = function(v, pbar, file, count, cb){
        return function(){
            if(v > count){
                cb();
            }else{
                if(pbar.id=='pbar4'){
                    //give this one a different count style for fun
                    var i = v/count;
                    pbar.updateProgress(i, Math.round(100*i)+'% completed...');
                }else{
                    pbar.updateProgress(v/count, 'Saving ' +  file);
                }
            }
       };
    };
    return {
        run : function(pbar, file, count, cb){
            var ms = 5000/count;
            for(var i = 1; i < (count+2); i++){
               setTimeout(f(i, pbar, file, count, cb), i*ms);
            }
        }
    };
}();
